<?php
    class APIBase {
		public $tag = "APIBase";
		public $uid;
		public $isLogin = true;
		public $isvip = false;
		public $response = array();
		public $param;

		public $mysql;
		public $data_redis;
		public $cache_redis;
		public $report_redis;
		public $redis;
	    public $http;
	    
	    
	    public function exec_logic() {
	        $this->init();
	        $this->checklogin();	
	        if ($this->before()) {
	            $this->logic();
	            $this->after();
	        }	 
	    }
	    
	    public function init() {
	        //入口参数日志
	        $this->d(" IP:".$this->getRealIp()." param:".json_encode($_GET));
	        if (isset($_GET['param'])) {
	            $this->param = (array)json_decode($_GET['param']);
	        }
	        //初始化redis
	        $this->initDataRedis();
	        $this->initCacheRedis();
	        $this->InitReportRedis();
	    }
	    
	    public function checklogin(){
	        if ($this->isLogin) {
	            if (!isset($_GET['uid']) or !isset($_GET['skey'])) {
	                $this->returnError(301, '用户不存在');//uid or skey must needed
	            }
	            if (empty($_GET['uid']) or empty($_GET['skey'])) {
	                $this->returnError(301, '用户不存在');//uid or skey error
	            }
	        
	            $skey = $this->data_redis->hGet("hu:{$_GET['uid']}", 'skey');
	        
	            //校验skey
	            if (Config::$debug) {
	                $this->uid = $_GET['uid'];
	            } else {
	                if ($skey == trim($_GET['skey']) ) {
	                    $this->uid = $_GET['uid'];
	                } else {
	                    $this->e('check skey', $skey.'-----'.$_GET['skey']);
	                    return $this->returnError(505, "登陆异常，请重新登陆");//skey error
	        
	                }
	            }
	        }
	    }
		
		public function before() {
			return true;
		}
		
		
		
		public function logic() {
		    
		    	
		}
		
		public function after() {
		    $this->deinitDataRedis();
		    $this->deinitCacheRedis();
		    $this->deinitReportRedis();
		}
		
		//检测是否是vip
		public function vipcheck($uid){
			$vipinfo = $this->data_redis->hmGet("hu:$uid",array('is_vip','vip_time'));
			//判断是否vip
			if(!$vipinfo['is_vip']){
				$this->returnError(330,'对不起，此功能只支持vip会员！');
			}
			
		}
		
		//初始化http
		public function inithttp() {	
			$this->http = new httpclient();
		}
		
		//关闭http资源
		public function deinithttp() {	
			$this->http->close();
		}
		
		//初始化mysql
		public function initMysql() {	
			$this->mysql = new Mysql();
			$ret = $this->mysql->connect(Config::$mysql_config);
			if (!$ret) {
				$this->returnError(3, "db connect error.");
				$this->e("mysql connect error.");
			}
		}
		
		//关闭mysql资源
		public  function deinitMysql() {
			$this->mysql->close();
		}
		
        //初始化redis
		public function initDataRedis(){
		    $redis = new RedisDriver();
		    $redis->InitDataRedis();
		    $this->data_redis = $redis->data_redis;
		}
		
		public function initCacheRedis(){
		    $redis = new RedisDriver();
		    $redis->InitCacheRedis();
		    $this->cache_redis = $redis->cache_redis;
		}
		
		public function InitReportRedis(){
		    $redis = new RedisDriver();
		    $redis->InitReportRedis();
		    $this->report_redis = $redis->report_redis;
		}
		
		
		//关闭redis资源
		public function deinitDataRedis(){
		    $this->data_redis->close();
		}
		public function deinitCacheRedis(){
		    $this->cache_redis->close();
		}
		public function deinitReportRedis(){
		    $this->report_redis->close();
		}

		public function returnData($data, $ret = 0, $desc = '') {
			header("Access-Control-Allow-Origin: *");
			$this->response['ret'] = $ret;
			$this->response['desc'] = $desc;
			$this->response['action'] = $this->tag ;
			
			if(isset($_GET['mainID'])){
        	  $this->response['mainID'] = (int)$_GET['mainID'] ;
			}
			if(isset($_GET['AssetID'])){
        	  $this->response['AssetID'] = (int)$_GET['AssetID'] ;
			}
			//$this->response['action'] = $this->tag;
			if ($data) {
				$this->response['data'] =$data;	
			}
			$msg = json_encode($this->response ,JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
			//$msg = $this->rc4('YUS!8W@zyl@k9NrQ',$msg);
			//$msg = base64_encode($msg);
			//$msg = str_replace(array('+'),array('-'),$msg);
			//$msg = substr($msg,1,strlen($msg));
			$this->d($msg);
			echo $msg;
			//echo strlen($msg);
			
			return;
		}
		
		public function returnDataAll($data, $ret = 0, $desc = '') {
			header("Access-Control-Allow-Origin: *");
			$this->response['ret'] = $ret;
			$this->response['desc'] = $desc;
			$this->response['action'] = $this->tag ;
			
			if(isset($_GET['mainID'])){
        	  $this->response['mainID'] = (int)$_GET['mainID'] ;
			}
			if(isset($_GET['AssetID'])){
        	  $this->response['AssetID'] = (int)$_GET['AssetID'] ;
			}
			
			$this->response['data'] = $data;
			$msg = json_encode($this->response ,JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
			//$msg = $this->rc4('YUS!8W@zyl@k9NrQ',$msg);
			//$msg = base64_encode($msg);
			
			echo  $msg;
			return;
		}

		
		public function returnError($code, $desc) {
			header("Access-Control-Allow-Origin: *");
			
			$this->returnData(null, $code, $desc);
			exit(0);
		}
		

		
		/*
		private function sendFlow($flow) {
			$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
			$msg = Config::$log_agent['pass'] . json_encode($flow);
			$len = strlen($msg);
			socket_sendto($sock, $msg, $len, 0, Config::$log_agent['host'], Config::$log_agent['port']);
			socket_close($sock);
		}
        */
		 
		//rc4加密
		public function rc4($pwd, $data){
			
			$key[] ="";
			$box[] ="";
			$cipher = "";
			$pwd_length = strlen($pwd);
			$data_length = strlen($data);
		 
			for ($i = 0; $i < 256; $i++)
			{
				$key[$i] = ord($pwd[$i % $pwd_length]);
				$box[$i] = $i;
			}
		 
			for ($j = $i = 0; $i < 256; $i++)
			{
				$j = ($j + $box[$i] + $key[$i]) % 256;
				$tmp = $box[$i];
				$box[$i] = $box[$j];
				$box[$j] = $tmp;
			}
		 
			for ($a = $j = $i = 0; $i < $data_length; $i++)
			{
				$a = ($a + 1) % 256;
				$j = ($j + $box[$a]) % 256;
		 
				$tmp = $box[$a];
				$box[$a] = $box[$j];
				$box[$j] = $tmp;
		 
				$k = $box[(($box[$a] + $box[$j]) % 256)];
				$cipher .= chr(ord($data[$i]) ^ $k);
			}
			 
			return $cipher;
         }
		
		
		//获取ip
		public function getRealIp(){
           $ip=false;
           if(!empty($_SERVER["HTTP_CLIENT_IP"])){
             $ip = $_SERVER["HTTP_CLIENT_IP"];
           }
           if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
             $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
             if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
             for ($i = 0; $i < count($ips); $i++) {
                if (!preg_match ("/^(10│172.16│192.168)./", $ips[$i])) {
                  $ip = $ips[$i];
                  break;
                }
             }
            }
			
            return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
        }
		
		
		public function d($msg) {
			Config::$loggerDebug->debug($this->tag, $msg);
		}
		public function i($msg) {
			Config::$logger->info($this->tag, $msg);
		}
		public function e($msg) {
			Config::$loggerError->error($this->tag, $msg);
		}
    }
